#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "udpconfigdialog.h"
#include "serialconfigdialog.h"

#include <QDebug>
#include <QDateTime>
#include <QMessageBox>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    configPath = new QString(":/resources/aircas.ini");
    loadConfig(*configPath);
    ui->setupUi(this);
    ui->useNoneRadioBtn->setVisible(false);
    initSlots();
    setEnabledForWidget();
}

MainWindow::~MainWindow()
{
    delete ui;
    delete serialCollector;
    delete udpCollector;
    delete basicConfig;
}

void MainWindow::loadConfig(QString &configPath) {
    QSettings *settings = new QSettings(configPath, QSettings::IniFormat);
    basicConfig = new Configurations(settings);
    qDebug() << basicConfig->ip;
}

void MainWindow::initSlots()
{
    qDebug("Init slots");
    connect(ui->actionUDPServerConfig, &QAction::triggered, this, &MainWindow::actionUDPServerConfig);
    connect(ui->actionSerialPortConfig, &QAction::triggered, this, &MainWindow::actionSerialConfig);

    connect(ui->udpRadioBtn, &QRadioButton::clicked, this, &MainWindow::switchCollector);
    connect(ui->serialRadioBtn, &QRadioButton::clicked, this, &MainWindow::switchCollector);

    connect(ui->startMeasBtn, &QToolButton::clicked, this, &MainWindow::startMeasBtnAction);
    connect(ui->stopMeasBtn, &QToolButton::clicked, this, &MainWindow::stopMeasBtnAction);


}

void MainWindow::updateBotLayout()
{
    if(ui->udpRadioBtn->isChecked()){
        ui->ph1Label->setText("CX1:");
        ui->ph2Label->setText("CX2:");
        ui->ph3Label->setText("CX21:");
        ui->ph4Label->setVisible(false);
    }
    if(ui->serialRadioBtn->isChecked()){
        ui->ph1Label->setText("Sat. Num:");
        ui->ph2Label->setText("Col. Timer:");
        ui->ph3Label->setText("Col. Status:");
        ui->ph4Label->setText("GPS Status:");
        ui->ph4Label->setVisible(true);
    }
}

void MainWindow::switchCollector()
{
    // Open UDP Server collector
    if (ui->udpRadioBtn->isChecked()){
        if (isUdp == false)
            udpCollector = new UDPServerThread(basicConfig->ip, basicConfig->port);

        if (udpCollector->initServer() == 0){
            ui->textBrowser->append(markTimer("INFO---UDP Server is ready with Port:" + QString::number(basicConfig->port)));
            isUdp = true;
            isSerial = false;
            updateBotLayout();
        } else {
            ui->useNoneRadioBtn->setChecked(true);
            ui->textBrowser->append(markTimer("ERROR---Unable to start the server!"));
        }
    }
    // Open Serial Port collector
    if (ui->serialRadioBtn->isChecked()){
        serialCollector = new SerialPortThread(basicConfig->serialNum, basicConfig->baudRate, basicConfig->parity,
                                               basicConfig->dataBit, basicConfig->stopBit);
        if(serialCollector->connectSerial() == 0) {
            ui->textBrowser->append(markTimer("INFO---Serial Port is ready!"));
            isSerial = true;
            isUdp = false;
            updateBotLayout();
        } else {
            ui->useNoneRadioBtn->setChecked(true);
            ui->textBrowser->append(markTimer("ERROR---Unable to start the serial port!"));
            QMessageBox::warning(this, "Error", "Unable to start the serial port! Please check Configuration!",
                                 QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
        }

    }
}

void MainWindow::actionUDPServerConfig()
{

    UDPConfigDialog dlg(basicConfig->ip, basicConfig->port);
    if (dlg.exec()) {
        basicConfig->ip = dlg.ipEdit->text();
        basicConfig->port = dlg.portEdit->text().toInt();
    }
}

void MainWindow::actionSerialConfig()
{
    SerialConfigDialog dlg(basicConfig->serialNum, basicConfig->baudRate, basicConfig->parity, basicConfig->dataBit, basicConfig->stopBit);
    if (dlg.exec()) {
        basicConfig->serialNum = dlg.serialNumBox->currentText();
        basicConfig->baudRate = dlg.baudRateBox->currentText().toInt();
        basicConfig->parity = dlg.parityBox->currentText();
        basicConfig->dataBit = dlg.dataBitBox->currentText().toInt();
        basicConfig->stopBit = dlg.stopBitBox->currentText();
    }
}

char* MainWindow::convertString(QString str)
{
    QByteArray strb = str.toLatin1();
    return strb.data();
}

void MainWindow::setEnabledForWidget(){
    ui->stopColBtn->setEnabled(false);
    ui->stopMeasBtn->setEnabled(false);
}

void MainWindow::onRecUDPData(udpInfo udpInfo) {
    qDebug() << "Main: " << udpInfo;
    if (count > 10)
        stopMeasBtnAction();
    if (count % 100 == 0)
        ui->textBrowser->clear();
//    ui->textBrowser->append(QString::number(count) + " Lat: " + QString::number(udpInfo->latitude));
    ui->countStr->setText(QString::number(count));
//    ui->latStr->setText(QString::number(udpInfo->latitude));
//    ui->lonStr->setText(QString::number(udpInfo->longitude));
//    ui->latStr->setText(QString::number(udpInfo->altitude));
//    ui->ph1Str->setText(QString::number(udpInfo->cx1));
//    ui->ph2Str->setText(QString::number(udpInfo->cx2));
//    ui->ph3Str->setText(QString::number(udpInfo->cx21));
    count = count + 1;
}

void MainWindow::startMeasBtnAction()
{
    if (isUdp) {
        count = 0;
        ui->textBrowser->append(markTimer("Start read udp information!"));
        udpCollector->start();
        connect(udpCollector, SIGNAL(parsedData(udpInfo)), this, SLOT(onRecUDPData(udpInfo)));
        ui->stopMeasBtn->setEnabled(true);
        ui->startMeasBtn->setEnabled(false);
    }
}

void MainWindow::stopMeasBtnAction()
{
    if (isUdp) {
        udpCollector->stopCollector();
        ui->stopMeasBtn->setEnabled(false);
        ui->startMeasBtn->setEnabled(true);
        ui->textBrowser->append(markTimer("Stop read udp information!"));
    }
}


void MainWindow::on_startColBtn_clicked()
{

}

void MainWindow::closeEvent(QCloseEvent *event)
{
    qDebug() << "Stop collector";

    if(udpCollector->isConnected){
        udpCollector->closeServer();
    }
    if(serialCollector->isReady){
        serialCollector->disconnect();
    }
}

QString markTimer(QString str)
{
    QDateTime curDateTime=QDateTime::currentDateTime();
    QString msg = curDateTime.toString("yyyy-MM-dd hh:mm:ss") + ":  " +str;
    return msg;
}
